package com.cuteboy.admin.controller;

import com.cuteboy.admin.service.SysRoleService;
import com.cuteboy.admin.service.SysUserRoleService;
import com.cuteboy.entity.SysRole;
import com.cuteboy.entity.SysUserRole;
import com.cuteboy.util.Constants;
import com.cuteboy.util.ValidateUtils;
import com.cuteboy.vo.ResponseVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("admin/user/role")
@Controller
public class SysUserRoleController {
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private SysRoleService sysRoleService;

    /**
     * 获取所有角色
     * 并根据用户名，通过checked字段标出用户已经拥有的角色
     * @param username
     * @return
     */
    @ResponseBody
    @PostMapping("/selectUserByUsername")
    public ResponseVO selectUserByUsername(String username) {
        Map<String,Object> map = new HashMap<String,Object>();
        // 获取所有角色
        List<SysRole> sysRoles = sysRoleService.selectAll();
        // 获取所有已关联用户的角色
        List<SysUserRole> userRoles = sysUserRoleService.selectByUsername(username);

        // 设置角色是否选中
        for (SysRole sysRole : sysRoles){
            for(SysUserRole userRole : userRoles){
                if(sysRole.getId() == userRole.getRoleId()){
                    sysRole.setChecked("checked");
                }
            }
        }
        return new ResponseVO(Constants.ResponseVo.Code.SUCCEESS, Constants.ResponseVo.msg.SUCCEESS, sysRoles);
    }

    /**
     * 根据用户，保存所有角色
     * @param username
     * @param roleIds
     * @return
     */
    @RequestMapping("userEditoyRoles")
    @ResponseBody
    public ResponseVO userEditoyRoles(@RequestParam String username, @RequestParam String roleIds){
        // 解析字符串
        String[] roleIdArr = roleIds.split(",");
        if (ValidateUtils.isNotNull(roleIdArr) && roleIdArr.length > 0){
            // 删除原数据
            sysUserRoleService.deleteByUsername(username);
            // 载入新数据
            for (String roleId : roleIdArr){
                SysUserRole userRole = new SysUserRole();
                userRole.setRoleId(Integer.valueOf(roleId));
                userRole.setUsername(username);
                sysUserRoleService.save(userRole);
            }
        } else {
            return new ResponseVO(Constants.ResponseVo.Code.ERROR, Constants.ResponseVo.msg.ERROR);
        }

        return new ResponseVO(Constants.ResponseVo.Code.SUCCEESS, Constants.ResponseVo.msg.SUCCEESS);
    }
}
